<?php


namespace Modules\Common\General\Security\Authorization\Concerns;


use Illuminate\Support\Facades\DB;
use Modules\Common\General\Security\Authorization\Casbin;

trait ManageUserPermission
{
    public function addPermissionsForUser(int $userId, array $permissionIds, int $branchId)
    {
        DB::transaction(function () use ($userId, $permissionIds, $branchId) {
            foreach ($permissionIds as $permissionId) {
                Casbin::addPermissionForUser("u$userId", "p$permissionId", "b$branchId");
            }
        });
    }

    public function deletePermissionsForUser(int $userId, array $permissionIds, $branchId)
    {
        DB::transaction(function () use ($userId, $permissionIds, $branchId) {
            foreach ($permissionIds as $permissionId) {
                Casbin::deletePermissionForUser("u$userId", "p$permissionId", "b$branchId");
            }
        });
    }

    public function getPermissionsForUser(int $userId)
    {
        return $this->filterVirtualPermissions(Casbin::getPermissionsForUser("u$userId"));
    }

    public function getImplicitPermissionsForUser(int $userId)
    {
        return $this->filterVirtualPermissions(Casbin::getImplicitPermissionsForUser("u$userId"));
    }

    public function getPermissionsForUserForPresentation(int $userId)
    {
        return $this->permissionsForPresentation(Casbin::getPermissionsForUser("u$userId"));
    }

    public function getImplicitPermissionsForUserForPresentation(int $userId)
    {
        return $this->permissionsForPresentation(Casbin::getImplicitPermissionsForUser("u$userId"));
    }

    public function getImplicitUsersForPermissionForPresentation(int $permissionId, int $branchId)
    {
        return $this->usersForPresentation(Casbin::getImplicitUsersForPermission("p$permissionId", "b$branchId"));
    }

    public function getImplicitUsersForPermission(int $permissionId, int $branchId)
    {
        return Casbin::getImplicitUsersForPermission("p$permissionId", "b$branchId");
    }


}
